import { onMounted, onUnmounted, isRef, unref,  watch } from 'vue'
import type { Ref } from 'vue'

export default function useEventListener(
    target: Ref<EventTarget | null> | EventTarget,
    event: string,
    handler: (event: Event) => any
) {
    if (isRef(target)) {
        watch(target, (newTarget, oldTarget) => {
            oldTarget?.removeEventListener(event, handler)
            newTarget?.addEventListener(event, handler)
        })
    } else {
        onMounted(() => {
            target.addEventListener(event, handler) 
        })
    }

    onUnmounted(() => {
        unref(target)?.removeEventListener(event, handler)
    })
}